<?php

namespace App\Http\Controllers;

use App\Library\Crypt\Wechat\WxBizMsgCrypt;
use App\Library\Util\SignUtil;
use App\Models\WechatLog;
use App\Models\WechatMenu;
use App\Models\WechatReplyConfig;
use App\Models\WechatUser;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use function simplehtmldom_1_5\str_get_html;

class WechatController extends Controller
{
    public function event(Request $request)
    {
        Log::info(json_encode($request->input()));
        $data = $request->input();
        if (isset($data['echostr'])) {
            $signature = $data["signature"];
            $timestamp = $data["timestamp"];
            $nonce = $data["nonce"];

            $token = 'lanzhan';
            $tmpArr = [$token, $timestamp, $nonce];
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                return $data['echostr'];
            } else {
                return false;
            }
        } else {
            $config = config('wechat.offical');
            $app = Factory::officialAccount($config);
            $app->server->push(function ($message) {
                file_put_contents('test.json', json_encode($message) . PHP_EOL, FILE_APPEND);
                $msgType = $message['MsgType'];
                WechatLog::query()->create([
                    'openid'      => $message['FromUserName'],
                    'merchant_id' => $message['ToUserName'],
                    'msg_type'    => $msgType,
                    'title'       => $this->getMsgTitle($msgType),
                    'content'     => $message,
                ]);
                switch ($msgType) {
                    case 'event':
                        return $this->eventHandle($message);
                    case 'text':
                    case 'image':
                    case 'voice':
                    case 'video':
                    case 'location':
                    case 'link':
                    case 'file':
                        return $this->commonHandle($message);
                    default:
                        return $this->commonHandle($message);
                }
            });
            $response = $app->server->serve();
            $response->send();

            return $response;
        }
    }

    public function getMsgTitle($msgType): string
    {
        switch ($msgType) {
            case 'event':
                return '收到事件消息';
            case 'text':
                return '收到文字消息';
            case 'image':
                return '收到图片消息';
            case 'voice':
                return '收到语音消息';
            case 'video':
                return '收到视频消息';
            case 'location':
                return '收到坐标消息';
            case 'link':
                return '收到链接消息';
            case 'file':
                return '收到文件消息';
            default:
                return '收到其它消息【' . $msgType . '】';
        }
    }

    public function commonHandle($message)
    {
        return WechatReplyConfig::query()->where('type', 1)->value('content') ?: null;
    }

    public function eventHandle($message)
    {
        $eventType = $message['Event'];
        $content = null;
        if ($eventType == 'subscribe') {
            WechatUser::query()->updateOrCreate([
                'openid'      => $message['FromUserName'],
                'merchant_id' => $message['ToUserName'],
            ], [
                'is_subscribe' => 1,
                'operate_time' => date('Y-m-d H:i:s'),
            ]);
            $content = WechatReplyConfig::query()->where('type', 2)->value('content') ?: null;
        } elseif ($eventType == 'unsubscribe') {
            WechatUser::query()->updateOrCreate([
                'openid'      => $message['FromUserName'],
                'merchant_id' => $message['ToUserName'],
            ], [
                'is_subscribe' => 0,
                'operate_time' => date('Y-m-d H:i:s'),
            ]);
        } else if ($eventType == "CLICK") {// 菜单事件
            $eventKey = $message['EventKey'];
            $content = WechatMenu::query()->where('custom_key', $eventKey)->value('content') ?: null;
        }
        return $content;
    }

    public function test()
    {
//        $config = config('wechat.offical');
//        $app = Factory::officialAccount($config);
//        $app->server->push(function ($message) {
//            $message['MsgType'] = 'text';
//            $message['FromUserName'] = 'gh_7a66a12ffcf8';
//            $message['ToUserName'] = 'oRzTN6Mb59vY29H2nN7s0L898L2k';
//            return '测试发送消息';
//        });
//        $response = $app->server->serve();
//        $response->send();

//        return $response;
        $data = $this->buildSign();
        return response()->json($data);
    }

    private function buildSign()
    {
        $str = '{"requestType":"1","activityType":"1","activityNo":"MR2024090910001","contentType":"","content":"fb0a372ca9907b1eb15fa6c511c094b39bb2ef629417d20cad83b0bb637b056c896344bcdf7760ba5b4266b7aca01c4f"}';
        $array = json_decode($str, true);
        $temp = $array;
        $temp['timestamp'] = time() * 1000;
        $sign = SignUtil::getInstance()->buildLzActivitySign($temp);
        return [
            'data' => [
                'sign'      => $sign,
                'timestamp' => $temp['timestamp'],
                'req'       => $array,
            ]
        ];
    }
}
